// 我的分析页面
import React from 'react';
import { connect } from 'react-redux';
import { RouteComponentProps } from 'react-router';
import { Row, Col, Space, Table, Input, Tooltip, Button, Popconfirm, message, Checkbox } from 'antd';
import { SearchOutlined, DeleteOutlined, BarChartOutlined, FontSizeOutlined, PlusCircleOutlined } from '@ant-design/icons';
import styles from './index.module.scss';
import {
	getCategoryTree,
	getChildAnalysePageList,
	// delAnalysePage,
	batchDelAnalysePage,
	updateShareConfig,
	setHomePage,
	delAnalyseCategory,
	replaceDataSet
} from 'src/services/AnalyseManage';
import { withRouter } from 'react-router-dom';
import TreeNode from 'src/pages/AnalyseManage/PredefinedReport/components/TreeNode';
import BdhButton from 'src/pages/Components/BdhButton';
import ShareModal from './components/ShareModal';
import AddNewFolder from './components/AddNewFolder';
import { FormInstance } from 'antd/lib/form';
import RenameModal from 'src/pages/AnalyseManage/Components/RenameModal';
import { encryptParam } from 'src/libs/paramsEncrypt';
import { ReplaceDataSet } from './components/ReplaceDataSet';
import { UploadDataSet } from './components/UploadDataSet';

interface listItemType {
	name: string;
	id: string;
	effect: string;
	isFile: boolean;
	des: string;
	isPublic: string;
	permittedAction: any;
}

interface RProps {
	btnAuth: any;
	match: {
		params: {
			id: string;
			isEdit: string;
		};
	};
}

interface IProps {
	record: listItemType;
	handleEdit: ( item: listItemType, isEdit: boolean ) => void;
	handleDelete: ( item: listItemType ) => void;
	shareConfig: ( item: listItemType ) => void;
	handleEditFolder: ( item: listItemType ) => void;
	handleDeleteFolder: ( item: listItemType ) => void;
	handleRename: ( item: listItemType ) => void;
	getDataSetList: ( item: listItemType ) => void;
	handleUpload: ( item: listItemType ) => void;
	btnAuth: any;
}

//	操作栏组件
const OperateComponent = React.memo( ( props: IProps ) => {
	const editAction = String( props.record.permittedAction ).indexOf( 'edit' ) > -1;
	const btnAuth = props.btnAuth.includes( 'bi_myAnalysis_action' );

	return btnAuth && editAction ? (
		<Space size="middle">
			<Tooltip placement="topRight" title="重命名">
				<Button
					type="text" icon={ <FontSizeOutlined className={ styles.green_btn }/> }
					onClick={ () => props.handleRename( props.record ) }></Button>
			</Tooltip>
			{
				props.record.isFile ?
					(
						<>
							<Tooltip placement="topRight" title="编辑">
								<Button
									type="text"
									icon={ <span className={ `iconfont bdhxiugai ${ styles.green_btn }` }></span> }
									onClick={ () => props.handleEditFolder( props.record ) }
								></Button>
							</Tooltip>
							<Tooltip placement="topRight" title="删除">
								<Popconfirm
									okText="确定"
									cancelText="取消"
									title="确定删除这一项？"
									placement="bottom"
									onConfirm={ () => props.handleDeleteFolder( props.record ) }
								>
									<Button
										type="text"
										icon={ <span className={ `iconfont bdhshanchu ${ styles.green_btn }` }></span> }></Button>
								</Popconfirm>
							</Tooltip>
						</>
					) :
					(
						<>
							<Tooltip placement="topRight" title="查看">
								<Button
									type="text"
									icon={ <span className={ `iconfont bdhchakanxiangqing ${ styles.green_btn }` }></span> }
									onClick={ () => props.handleEdit( props.record, false ) }
								></Button>
							</Tooltip>
							<Tooltip placement="topRight" title="查看权限">
								<Button
									type="text"
									icon={ <span className={ `iconfont bdhquanxian ${ styles.green_btn }` }></span> }
									onClick={ () => {
										props.shareConfig( props.record );
									} }
								></Button>
							</Tooltip>
							<Tooltip placement="topRight" title="编辑">
								<Button
									type="text"
									icon={ <span className={ `iconfont bdhxiugai ${ styles.green_btn }` }></span> }
									onClick={ () => props.handleEdit( props.record, true ) }
								></Button>
							</Tooltip>
							<Tooltip placement="topRight" title="数据集替换">
								<Button
									type="text"
									icon={ <span className={ `iconfont bdhshuaxin ${ styles.green_btn }` }></span> }
									onClick={ () => props.getDataSetList( props.record ) }
								></Button>
							</Tooltip>
							<Tooltip placement="topRight" title="数据集上传">
								<Button
									type="text"
									icon={ <span className={ `iconfont bdhshangchuan ${ styles.green_btn }` }></span> }
									onClick={ () => props.handleUpload( props.record ) }
								></Button>
							</Tooltip>

							<Tooltip placement="topRight" title="删除">
								<Popconfirm
									okText="确定"
									cancelText="取消"
									title="确定删除这一项？"
									placement="bottom"
									onConfirm={ () => props.handleDelete( props.record ) }
								>
									<Button
										type="text"
										icon={ <span className={ `iconfont bdhshanchu ${ styles.green_btn }` }></span> }></Button>
								</Popconfirm>
							</Tooltip>
						</>
					)
			}
		</Space>
	) : (
		<Space size="middle">
			{
				!props.record.isFile && (
					<>
						<Tooltip placement="topRight" title="查看">
							<Button
								type="text"
								icon={ <span className={ `iconfont bdhchakanxiangqing ${ styles.green_btn }` }></span> }
								onClick={ () => props.handleEdit( props.record, false ) }
							></Button>
						</Tooltip>
						<Tooltip placement="topRight" title="查看权限">
							<Button
								type="text"
								icon={ <span className={ `iconfont bdhquanxian ${ styles.green_btn }` }></span> }
								onClick={ () => {
									props.shareConfig( props.record );
								} }
							></Button>
						</Tooltip>
					</>
				) 
			}
		</Space>
	);
} );
OperateComponent.displayName = 'OperateComponent';

class MyAnalyse extends React.Component<RouteComponentProps & RProps> {

	state: any = {
		data: [], //	table数据
		treeData: [],
		activeTreeNode: '',
		keyword: '',
		timer: null,
		tableLoading: false,
		page: 1,
		pageSize: 10,
		total: 0,
		selectedRowKeys: [],
		shareModalVisible: false,
		shareConfigPageId: '',
		isAddFolderModalShow: false,
		fileData: {},
		folderFormData: {},
		actionType: null,
		modalVisible: false,
		currentModalData: {}, // 操作栏选中的数据
		// 数据集替换/上传
		replaceModalShow: false,
		uploadModalShow: false,
		tableList: [],
	};
	formRef = React.createRef<FormInstance>();
	//	列表表头配置
	columns = [
		{
			title: '报表名称',
			dataIndex: 'name',
			width: 200,
			render: ( text, record ) => {
				let icon;
				const paddingLeft = record.isFile ? 0 : '24px';
				if ( record.isFile ) {
					icon = <span className={ 'iconfont bdhwenjianjiadakai' } style={ { marginRight: '10px' } }></span>;
				} else {
					icon = <BarChartOutlined className={ styles.green_btn } style={ { marginRight: '10px' } } />;
				}
				return (
					<div style={ { paddingLeft } }>
						{
							record.isFile ? ( <>{ icon }{ record.name }</> ) : (
								<span className="bdh-link" onClick={() => this.handleEdit( record, false )}>
									{ icon }{ record.name }
								</span>
							)
						}
					</div>
				);
			},
		},
		{
			title: '报表编码',
			dataIndex: 'code',
			width: 100,
		},
		{
			title: '描述',
			dataIndex: 'des',
			width: 150,
		},
		{
			title: '创建人',
			dataIndex: 'createUserName',
			width: 100,
		},
		{
			title: '最后更新时间',
			dataIndex: 'modifiedDate',
			width: 150,
		},
		{
			title: '更新人',
			dataIndex: 'modifiedUserName',
			width: 100,
		},
		{
			title: '设为首页',
			dataIndex: 'homePage',
			width: 100,
			align: 'center' as 'center',
			render: ( text, record ) => {
				const btnAuth = this.props.btnAuth;
				let checked = text === '1' ? true : false;
				if ( record.isFile ) return null;
				return (
					<>
						<Popconfirm
							disabled={ checked || !btnAuth.includes( 'bi_myAnalysis_action' ) }
							okText="确定"
							cancelText="取消"
							title="确定要设置为首页？"
							placement="top"
							onConfirm={ () => this.changeHomePage( true, record ) }>
							<Checkbox checked={ checked } disabled={ checked || !btnAuth.includes( 'bi_myAnalysis_action' ) }></Checkbox>
						</Popconfirm>
					</>
				);
			},
		},
		{
			title: '操作',
			key: 'action',
			width: 360,
			// eslint-disable-next-line react/display-name
			render: ( record: listItemType ) => (
				<OperateComponent
					record={ record }
					handleEdit={ this.handleEdit }
					handleDelete={ this.handleDelete }
					shareConfig={ this.shareConfig }
					handleEditFolder={ this.handleEditFolder }
					handleDeleteFolder={ this.handleDeleteFolder }
					getDataSetList={this.getDataSetList}
					handleUpload={this.handleUpload}
					handleRename={ this.handleRename }
					btnAuth={ this.props.btnAuth }
				></OperateComponent>
			),
		},
	];

	// 设为主页
	changeHomePage = ( checked, row ) => {
		// console.log( checked, row );
		let oldData = JSON.parse( JSON.stringify( this.state.data ) );
		let data = JSON.parse( JSON.stringify( this.state.data ) );

		row.homePage = checked ? '1' : '0';
		data.forEach( ( item ) => {
			if ( item.id === row.id ) {
				item.homePage = row.homePage;
			} else if ( checked ) {
				item.homePage = '0';
			}
		} );
		this.setState( {
			data: [ ...data ],
		} );
		setHomePage( { data: row.id } )
			.then( ( res ) => {
				if ( res.data.success ) {
					message.success( '设置首页成功!' );
				} else {
					message.error( '设置首页失败!' );
					this.setState( {
						data: oldData,
					} );
				}
			} )
			.catch( ( err ) => {
				// message.error( '设置首页失败!' );
				this.setState( {
					data: oldData,
				} );
			} );
	};

	getDataSetList = async ( item: listItemType ) => {
		this.setState( { replaceModalShow: true, currentModalData: item } );
	};

	handleReplace = async( arr ) => {
		const data = {
			pageId: this.state.currentModalData.id,
			replaceItemDtoList: arr
		};
		const res = await replaceDataSet( data );
		if ( res.data && res.data.success ) {
			message.success( '替换成功' );
			this.setState( { replaceModalShow: false } );
		}
	};

	handleUpload = ( item: listItemType ) => {
		this.setState( { uploadModalShow: true } );
	};

	//	编辑
	handleEdit = ( item: listItemType, isEdit ) => {
		let editPath = '/analyseManage/editReport';
		let previewPath = '/analyseManage/previewReport';
		const type = isEdit ? 'EDIT' : 'PUBLISH';
		window.open(
			`${ window.location.origin }${ isEdit ? editPath : previewPath }/${ encryptParam( item.id ) }/${ encryptParam( isEdit ) }/${encryptParam( type )}`,
			'_blank' );
	};

	handleEditFolder = ( item: listItemType ) => {
		this.setState( {
			actionType: 'EDIT',
			folderFormData: item,
			isAddFolderModalShow: true
		} );
	}

	//	重命名
	handleRename = ( item: listItemType ) => {
		console.log( item );
		const modalData = {
			name: item.name,
			des: item.des,
			id: item.id,
			isFile: item.isFile
		};
		this.setState( {
			currentModalData: modalData,
			modalVisible: true
		} );
	};

	//	删除
	handleDelete = async ( item: listItemType ) => {

		let info = await batchDelAnalysePage( {
			type: 'PUBLISH',
			ids: [ item.id ] // this.state.selectedRowKeys,
		} );
		// const info = await delAnalysePage( item.id );
		if ( info.data && info.data.success ) {
			message.success( '删除成功' );
			this.getList();
		}
	};

	handleDeleteFolder = async ( item: listItemType ) => {
		const response = await delAnalyseCategory( item.id );
		if ( response.data && response.data.success ) {
			this.loadDatas();
			message.success( '操作成功' );
		}
	}

	shareConfig = ( item: listItemType ) => {
		if ( item.isPublic ) {
			this.setState( {
				shareModalVisible: true,
				shareConfigPageId: item.id,
				isPublic: item.isPublic
			} );
		} else {
			message.error( '报表未发布' );
		}
	};

	updateShareConfig = async ( type, password ) => {
		console.log( type, password );
		const data = await updateShareConfig( {
			type,
			password,
			pageId: this.state.shareConfigPageId,
		} );

		if ( data.data.success ) {
			message.success( '修改成功' );
			this.hideModal();
		}
	};

	//	隐藏modal
	hideModal = () => {
		this.setState( {
			shareModalVisible: false,
			shareConfigPageId: '',
		} );
	};

	componentDidMount() {
		this.loadDatas();
	}

	componentDidUpdate( prevProps: Readonly<RouteComponentProps & RProps>, prevState: Readonly<{}>, snapshot?: any ): void {
		if ( prevProps.match.params.id !== this.props.match.params.id ) this.loadDatas();
	}

	loadDatas = async () => {
		let response: any = {};
		// 我的分析
		response = await getCategoryTree( { type: 'CUSTOMER' } );
		if ( response.data && response.data.success ) {
			if ( response.data.data.length > 0 ) {
				const fileData = { ...response.data.data[ 0 ], isFile: true };
				this.setState( {
					treeData: response.data.data || [],
					fileData
				}, () => {
					this.clickNode( fileData );
				} );
			}
		}
	};

	clickNode = ( item ) => {
		this.setState(
			{
				activeTreeNode: item.id,
				tableLoading: true,
				fileData: item,
				page: 1
			},
			() => {
				this.getList();
			}
		);
	};

	getList = async () => {
		let response = await getChildAnalysePageList( {
			categoryId: this.state.activeTreeNode,
			name: this.state.keyword,
			page: this.state.page,
			size: this.state.pageSize,
		} );
		if ( response.data && response.data.success ) {
			// let dates = response.data.data.rows;
			let dates = this.state.page === 1 ?
				[ this.state.fileData, ...response.data.data.rows ] : response.data.data.rows;
			// console.log( dates );
			this.setState( { data: dates, total: response.data.data.total + 1 } );	//	第一条文件夹算作一条数据
		}

		this.setState( {
			tableLoading: false,
		} );
	};

	//	切换页码
	handlePageChange = ( pageNumber: number ) => {
		this.setState(
			{
				page: pageNumber,
			},
			() => {
				this.getList();
			}
		);
	};

	//	修改每页数量
	setPageSize = ( size: number ) => {
		this.setState( {
			pageSize: size,
		} );
	};

	//	输入框搜索
	handleSearchInput = ( e ) => {
		e.persist();

		let value = e.target.value;
		this.setState( {
			keyword: value,
		} );

		if ( this.state.timer ) clearTimeout( this.state.timer );
		let timer = setTimeout( () => {
			this.getList();
		}, 300 );
		this.setState( {
			timer: timer,
		} );
	};

	//	批量删除
	handleBatchDel = async () => {
		let response = await batchDelAnalysePage( {
			ids: this.state.selectedRowKeys,
			type: 'PUBLISH'
		} );
		if ( response.data && response.data.success ) {
			message.success( '删除成功' );
			this.getList();
			this.setState( {
				selectedRowKeys: [],
			} );
		}
	};

	handleSelectionChange = ( selectedRowKeys ) => {
		this.setState( { selectedRowKeys } );
	};

	onAddFolderSuccess = ( id ) => {
		this.setState( { isAddFolderModalShow: false } );
		this.loadDatas();
		message.success( '设置成功!' );
	}

	toggleRenameModalVisible = ( isVisible: boolean, isLoadData: boolean = false ) => {
		this.setState( { modalVisible: isVisible } );
		if( isLoadData ) this.loadDatas();
	};

	render() {
		const btnAuth = this.props.btnAuth;

		return (
			<>
				<div className={ styles.report_contanier }>
					<div className={ styles.tree_container }>
						<p>我的分析</p>
						<div>
							{ this.state.treeData.map( ( item, index: number ) => (
								<TreeNode
									activeNodeId={ this.state.activeTreeNode }
									key={ index }
									id={ item.id }
									label={ item.name }
									handleClick={ () => this.clickNode( { ...item, isFile: true } ) }
								></TreeNode>
							) ) }
						</div>
					</div>

					<div className={ styles.table_container }>
						<Row justify="space-between">
							<Col span={ 12 } style={ { textAlign: 'left' } }>
								{
									btnAuth.includes( 'bi_myAnalysis_addFolder' ) && (
										<BdhButton
											align="horizontal"
											label="新建文件夹"
											type="primary"
											icon={ <PlusCircleOutlined /> }
											onClick={ () => this.setState( { isAddFolderModalShow: true, actionType: 'ADD' } ) }
										></BdhButton>
									)
								}
								{
									btnAuth.includes( 'bi_myAnalysis_batchDel' ) && (
										<Popconfirm
											okText="确定"
											cancelText="取消"
											title="确定删除选中数据？"
											placement="bottom"
											onConfirm={ this.handleBatchDel }
										>
											{/* <BdhButton
												align="horizontal"
												label="批量删除"
												className="grey-transpanent"
												onClick={ null }
												icon={ <DeleteOutlined/> }
											></BdhButton> */}
											<Button onClick={ null } icon={ <DeleteOutlined/> }>批量删除</Button>
										</Popconfirm>
									)
								}
							</Col>
							<Col xs={ 24 } sm={ 6 } md={ 6 } lg={ 6 } xl={ 6 } style={ { textAlign: 'right' } }>
								<Input placeholder="请输入报表名称回车搜索" allowClear onChange={ this.handleSearchInput } prefix={ <SearchOutlined/> }/>
							</Col>
						</Row>

						<Table
							// key={new Date().getTime()}
							loading={ this.state.tableLoading }
							childrenColumnName="null"
							rowSelection={ { type: 'checkbox', onChange: this.handleSelectionChange } }
							scroll={ { x: '100%', y: '470px' } }
							tableLayout="fixed"
							columns={ this.columns }
							dataSource={ this.state.data }
							className={ styles.table }
							bordered={ true }
							rowKey={ ( row: listItemType ) => row.id }
							rowClassName={ ( row ) => row.isFile ? 'row-folder' : '' }
							size="middle"
							pagination={ {
								showSizeChanger: true,
								pageSize: this.state.pageSize,
								total: this.state.total,
								onChange: this.handlePageChange,
								onShowSizeChange: ( current, size ) => this.setPageSize( size ),
								showTotal: ( total ) => `共 ${ total } 条`,
							} }
						/>
					</div>
				</div>
				{ this.state.replaceModalShow && (
					<ReplaceDataSet
						currentModalData={this.state.currentModalData}
						modalVisible={this.state.replaceModalShow}
						handleReplace={this.handleReplace}
						closeModal={() => this.setState( { replaceModalShow: false } )}></ReplaceDataSet>
				)}
				{ this.state.uploadModalShow && (
					<UploadDataSet modalVisible={this.state.uploadModalShow}
						closeModal={() => this.setState( { uploadModalShow: false } )}></UploadDataSet>
				)}
				{ this.state.shareConfigPageId && (
					<ShareModal
						pageId={ this.state.shareConfigPageId }
						shareModalVisible={ this.state.shareModalVisible }
						isPublic={ this.state.isPublic }
						handleOk={ this.updateShareConfig }
						handleCancel={ this.hideModal }
					></ShareModal>
				) }
				{
					this.state.isAddFolderModalShow && (
						<AddNewFolder
							actionType={ this.state.actionType }
							modalVisible={ this.state.isAddFolderModalShow }
							initialValues={ this.state.folderFormData }
							onSuccess={ ( id ) => this.onAddFolderSuccess( id ) }
							onCancel={ () => this.setState( { isAddFolderModalShow: false } ) }
						></AddNewFolder>
					)
				}
				<RenameModal
					modalVisible={this.state.modalVisible}
					toggleVisible={this.toggleRenameModalVisible}
					currentModalData={this.state.currentModalData}></RenameModal>
			</>
		);
	}
}

//	映射state到当前组件
const mapStateToProps = ( state ) => {
	return {
		btnAuth: state.btnAuth,
	};
};

export default withRouter( connect( mapStateToProps )( MyAnalyse ) );
